from django.shortcuts import render,redirect
from App001 import  models
from django.core.validators import ValidationError
from django.core.validators import RegexValidator
# from App001.views import depart
# 靓号的显示
def pretty_list(request):
    # 添加排序的规则，可以按照id或者是level,如果前边有负号说明是倒序的

    # for i in range(200):
    #     models.PrettyNum.objects.create(mobile="1678",price=999,level=2,status=1)


    data_dict={}
    search_data= request.GET.get('q',"")
    if search_data:
        data_dict["mobile__contains"]=search_data

    page = int(request.GET.get('page', 1))
    start = (page - 1) * 10
    end = page * 10

    queryset=models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]
    # quary = models.PrettyNum.objects.all().order_by("-id")

    return render(request, 'pretty_list.html', {"quaryset": queryset,"search_data":search_data})

# def pretty_add(request):
#
#         return render(request,'pretty_add.html')
from django import forms


class PrettyModelForm(forms.ModelForm):
    # mobile=forms.CharField(disabled=True,label='手机号')  #进行锁定，就是不可以进行再次更改
    # mobile=forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$'),"手机号格式",]
    # )
    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level","status"]
        widgets = {
            # 通过属性去定义这些框框的形状，注意是输入框还是选择框，需要注意
            "mobile": forms.TextInput(attrs={"class": "form-control"}),
            "price": forms.TextInput(attrs={"class": "form-control"}),
            "level": forms.Select(attrs={"class": "form-control"}),
            "status": forms.Select(attrs={"class": "form-control"}),
        }
        # def __init__(self,*args,**kwargs):
        #     super().__init__(*args,**kwargs)
        #     for name,field in self.fields.items():
        #         field.widgets.attrs={"class": "form-control","placeholder":field.labels}
        #验证方法

        def clean_mobile(self):
            text_mobile=self.cleaned_data['mobile']
            exist=models.PrettyNum.objects.filter(mobile=text_mobile).exists()
            if exist:
                raise ValidationError("手机号已存在")

            return  text_mobile

def pretty_model_form_add(request):
    """进行靓号的添加，(ModelForm版本)"""
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, "pretty_model_form_add.html", {'form': form})

    # 用户使用post请求来进行校验数据：
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        # 进行数据的校验，然后进行保存
        form.save()  # 保存直接到数据库
        return redirect('/pretty/list/')
    else:
        # 返回这个页面，然后通过前端的部分去进行错误信息展示
        return render(request, "pretty_model_form_add.html", {'form': form})
def pretty_edit(request,nid):
    """对于用户界面进行编辑

    其实你也应该在这添加一个正则表达式的，则用来
    """
    row_object=models.PrettyNum.objects.filter(id=nid).first()
    if request.method =="GET":
        form = PrettyModelForm(instance=row_object)

        return render(request, "pretty_edit.html", {'form': form})
    form = PrettyModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, "pretty_edit.html", {'form': form})

# 进行数据的删除
def pretty_delete(request,nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')